package com.heba.fragment.product;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.ItemShopObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import easypermission.EasyPermission;
import easypermission.GrantResult;
import easypermission.Permission;
import easypermission.PermissionRequestListener;

public class ProductShopListFragment extends BaseFragment {
    private LocationListener gpsLocationListener;
    private LocationListener networkListener;
    private LocationManager locationManager;
    private Location mLocation;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;
    private List<ItemShopObject> shopDetailObjectList;
    public int type ;
    public String productID;
    public double lat;
    public double lng;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.product_shop_list_fragment, container, false);

        initView(view);
        getLocationData();
        return view;
    }
    public void  initView(View view){
        shopDetailObjectList = new ArrayList<>();
//        view_background = view.findViewById(R.id.view_background);
        recycleAdapter = new QuickAdapter<ItemShopObject>(shopDetailObjectList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_shop;
            }

            @Override
            public int getItemCount() {
                return shopDetailObjectList.size();
            }

            @Override
            public void convert(VH holder, ItemShopObject data, int position) {
                ItemShopObject obj =  data;
                System.out.println("refreshdata___");
                ImageView imageView = holder.getView(R.id.goods_img);
                GlideUtil.loadImageWithDefaultPlaceHolder(getContext(), obj.getIcon(), imageView);
                TextView shopName = holder.getView(R.id.shop_name);
                shopName.setText(obj.getNickname());
                TextView addressTxt = holder.getView(R.id.address_txt);

                addressTxt.setText(obj.getDistance()+getContext().getString(R.string.shop_distance_km)+" - "+obj.getDistrict()+obj.getStreet()+obj.getEstate()+obj.getBuilding()+","+obj.getFloor()+getString(R.string.Floor)+","+obj.getUnit()+getString(R.string.Unit));
                TextView priceTxt = holder.getView(R.id.money_txt);
//                if(obj.getMinPrice().equals("0.00")&&obj.getMaxPrice().equals("0.00")){
//                    priceTxt.setText("$ - ");
//                }else if (obj.getMinPrice().equals(obj.getMaxPrice())){
//                    if(!obj.getMinPrice().equals("0.00")){
//                        priceTxt.setText(obj.getMinPrice());
//                    }
//                }else{
//
//                    priceTxt.setText("$"+obj.getMinPrice()+" - "+"$"+obj.getMaxPrice());
//                }
                priceTxt.setText("$"+(obj.getPrice()==null?"-":obj.getPrice()));
                holder.itemView.setOnClickListener(view1 -> {
                    ///打開商家詳情
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.SEND_USER_ID, obj.getUserID());
                    openActivity(BusinessPersonActivity.class, bundle);

                });
            }

            @Override
            public void onBindViewHolder(VH holder, int position) {
                super.onBindViewHolder(holder, position);
            }
        };
        recyclerView = view.findViewById(R.id.recyclerView);
        refreshLayout = view.findViewById(R.id.refreshLayout);



        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        //设置动画执行时间为0  防止局部刷新时闪烁
        recyclerView.getItemAnimator().setChangeDuration(0);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            shopDetailObjectList.clear();
            getShopListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;

            getShopListData();
        });

    }
    private void getLocationData() {
        EasyPermission.with(getActivity())
                .addPermissions(Permission.Group.LOCATION)      //申请定位权限组
                .request(new PermissionRequestListener() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onGrant(Map<String, GrantResult> result) {
                        System.out.println("111111111111111111");
                        System.out.println(result);
                        Criteria criteria = new Criteria();
                        criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
                        criteria.setAltitudeRequired(false);//无海拔要求   criteria.setBearingRequired(false);//无方位要求
                        criteria.setCostAllowed(true);//允许产生资费   criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
                        locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
                        // 获取最佳服务对象
                        String provider = locationManager.getBestProvider(criteria, true);


                        networkListener = new LocationListener() {

                            @Override
                            public void onLocationChanged(Location location) {

                                mLocation = location;
                                locationManager.removeUpdates(this);
                                locationManager.removeUpdates(gpsLocationListener);
                                if (mLocation != null) {
                                    lat = mLocation.getLatitude();
                                    lng = mLocation.getLongitude();
                                    getShopListData();
                                }

                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }

                            @Override
                            public void onProviderEnabled(String provider) {
                            }

                            @Override
                            public void onProviderDisabled(String provider) {
                                String string = provider;
                                System.out.println(provider);
                            }

                        };
                        gpsLocationListener = new LocationListener() {

                            @Override
                            public void onLocationChanged(Location location) {

                                locationManager.removeUpdates(networkListener);
                                mLocation = location;
                                if (mLocation != null) {
                                    lat = mLocation.getLatitude();
                                    lng = mLocation.getLongitude();
                                    getShopListData();
                                }
                            }

                            @Override
                            public void onProviderDisabled(String provider) {
                            }

                            @Override
                            public void onProviderEnabled(String provider) {
                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }
                        };

                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, gpsLocationListener);
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, networkListener);
                        locationManager.getLastKnownLocation(provider);
                    }

                    @Override
                    public void onCancel(String stopPermission) {
                        //在addRequestPermissionRationaleHandler的处理函数里面调用了NextAction.next(NextActionType.STOP,就会中断申请过程，直接回调到这里来
                    }

                });


    }
    public void getShopListData() {

        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p",Page);
        params.put("pp",20);
        params.put("Lat",lat);
        params.put("Lng",lng);
        params.put("Type",type);
        params.put("ProductID",productID);
        params.put("UserID",Cfg.UserID);
        client.get(Cfg.BaseUrl + "/Shop/GetLists", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getContext()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");

                            if (array.length() > 0) {
                                List<ItemShopObject> list = new Gson().fromJson(array.toString(), new TypeToken<List<ItemShopObject>>() {
                                }.getType());
                                shopDetailObjectList.addAll(list);
                            }
                            System.out.println("222222222222");
                            System.out.println("admind"+shopDetailObjectList);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();

                        recycleAdapter.notifyDataSetChanged();

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                    }

                });
    }
}
